package org.example.top41_80;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class main46 {
    //下一个排列

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums =new int[n];
        for(int i=0;i<n;i++){
            nums[i]=sc.nextInt();
        }
        nextpart(nums);
        for (int num:nums){
            System.out.println(num);
        }
    }

    private static void nextpart(int[] nums) {
        int n = nums.length;
        int i = n - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        if (i >= 0) {
            int j = n - 1;
            while (nums[j] <= nums[i]) {
                j--;
            }
            swap(nums, i, j);
        }
        reverses(nums, i + 1, n - 1);
    }

    private static void reverses(int[] nums, int l, int r) {
        while (l < r) {
            swap(nums, l++, r--);
        }
    }

    private static void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
